<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class News extends Model
{
    protected $table = 'new';
    protected $casts = [
        'updated_at' => 'datetime:Y-m-d H:i:s',
        'created_at' => 'datetime:Y-m-d H:i:s',
    ];
    protected $fillable = [
        'uid', 'title', 'body', 'category_id', 'excerpt', 'images', 'videos'
    ];

    //新闻对应的评论
    public function Comments()
    {
        return $this->hasMany(Comment::class);
    }

    //新闻所属分类
    public function category()
    {
        return $this->belongsTo(New_Category::class, 'category_id', 'id');
    }

    //新闻所属用户
    public function user()
    {
        return $this->belongsTo(User::class, 'uid', 'id');
    }

    public function scopeWithOrder($query, $order)
    {

        // 不同的排序，使用不同的数据读取逻辑
        switch ($order) {
            case 'recent':
                $query->recent();
                break;

            default:
                $query->recentReplied();
                break;
        }
    }

    public function scopeRecentReplied($query)
    {
        // 当话题有新回复时，我们将编写逻辑来更新话题模型的 reply_count 属性，
        // 此时会自动触发框架对数据模型 updated_at 时间戳的更新
        return $query->orderBy('updated_at', 'desc');
    }

    public function scopeRecent($query)
    {
        // 按照创建时间排序
        return $query->orderBy('created_at', 'desc');
    }

    public function link($params = [])
    {
        return route('topics.show', array_merge([$this->id, $this->slug], $params));
    }

    //新闻点击数递加
    public function updateViewCount()
    {
        $this->view_count = $this->view_count + 1;
        $this->save();
    }
    public function updateReplyCount()
    {
        $this->reply_count = $this->replies->count();
        $this->save();
    }
}
